﻿using System;
using System.Collections.Generic;
using System.Collections;
//using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace AnnotatedChunks
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creates a PDF file with annotations.
            // 
            // @param args:  no arguments needed here

            Console.WriteLine("Chapter 15: example Annotations");
            Console.WriteLine("-> Creates a PDF file with annotations;");
            Console.WriteLine("-> files generated:");
            Console.WriteLine("   annotated_chunks.pdf");
            // step 1: creation of a document-object
            Document document = new Document();
            try
            {
                // step 2:
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("annotated_chunks.pdf", FileMode.Create));
                // step 3:
                document.Open();
                // step 4:
                PdfAnnotation text = PdfAnnotation.CreateText(writer, new Rectangle(200f, 250f, 300f, 350f), "Fox", "The fox is quick", true, "Comment");
                PdfAnnotation attachment = PdfAnnotation.CreateFileAttachment(writer, new Rectangle(100f, 650f, 150f, 700f), "Image of the fox and the dog", getBytesFromFile(@"D:\Temp\DD.jpg"), null, "Store.jpg");
                PdfAnnotation javascript = new PdfAnnotation(writer, 200f, 550f, 300f, 650f, PdfAction.JavaScript("app.alert('Wake up dog!');\r", writer));
                Chunk fox = new Chunk("quick brown fox").SetAnnotation(text);
                Chunk jumps = new Chunk(" jumps over ").SetAnnotation(attachment);
                Chunk dog = new Chunk("the lazy dog").SetAnnotation(javascript);
                document.Add(fox);
                document.Add(jumps);
                document.Add(dog);
            }

            catch (Exception de)
            {
                Console.Error.WriteLine(de.Message);
            }

            // step 5: we close the document
            document.Close();

            Console.ReadLine();
        }

        private static byte[] getBytesFromFile(string fileName)
        {
            FileStream ifs = new FileStream(fileName, FileMode.Open);
            long length = ifs.Length;
            byte[] bytes = new byte[(int)length];
            int offset = 0;
            int numRead = 0;

            while (offset < bytes.Length && (numRead = ifs.Read(bytes, offset, bytes.Length - offset)) >= 0)
            {
                offset += numRead;
            }

            if (offset < bytes.Length)
            {
                Console.WriteLine("Could not completely read file " + ifs.Name);
            }

            ifs.Close();
            return bytes;
        }
    }
}
